package com.cskaoyan.app.wxcontroller;


import com.cskaoyan.app.bean.common.BaseRespVo;
import com.cskaoyan.app.bean.common.CommonData;
import com.cskaoyan.app.bean.po.MarketAddress;
import com.cskaoyan.app.exception.ValidationException;
import com.cskaoyan.app.util.ValidationUtil;
import com.cskaoyan.app.wxservice.WxAddrService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;


@RestController
@RequestMapping("wx/address")
public class WxAddrController {

    @Autowired
    private WxAddrService addrService;

    @GetMapping("list")
    public BaseRespVo<CommonData<MarketAddress>> listAddress() {
        Subject subject = SecurityUtils.getSubject();
        Integer userid = (Integer) subject.getSession().getAttribute("userid");
        CommonData<MarketAddress> data = addrService.getAddrByUserId(userid);
        return BaseRespVo.ok(data);
    }

    @PostMapping("save")
    public BaseRespVo<Object> save(@RequestBody @Validated MarketAddress address,
        BindingResult bindingResult) throws ValidationException {
        ValidationUtil.valid(bindingResult);
        Subject subject = SecurityUtils.getSubject();
        Integer userid = (Integer) subject.getSession().getAttribute("userid");
        address.setUserId(userid);
        addrService.saveAddr(address);
        return BaseRespVo.ok();
    }

    @PostMapping("delete")
    public BaseRespVo<Object> delete(@RequestBody Map<String, Integer> map) {
        if (map == null) {
            return BaseRespVo.invalidParameter("参数格式不正确");
        }
        Integer id = map.get("id");
        if (id == null) {
            return BaseRespVo.invalidParameter("id不能为空");
        }
        addrService.deleteById(id);
        return BaseRespVo.ok();
    }

    @GetMapping("detail")
    public BaseRespVo<Object> detail(Integer id) {
        if (id == null) {
            return BaseRespVo.invalidParameter("id不能为空");
        }
        MarketAddress address = addrService.getDetailById(id);
        return BaseRespVo.ok(address);
    }
}
